﻿using Estsh.Core.Controllers;
using Estsh.Core.IServices;
using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Model.Result;
using Estsh.Core.Models;
using Estsh.Core.Services;
using Estsh.Core.Util;
using Estsh.Core.Wms.IServices;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Text.Json;

/***************************************************************************************************
 *
 * 更新人：sitong.dong
 * 描述：工单管理
 * 修改时间：20223.03.09
 * 修改日志：系统迭代升级
 *
 **************************************************************************************************/
namespace Estsh.Core.Web.Plugin.Wms.Areas.mes.Controllers.WorkOrder
{

    /// <summary>
    /// 
    /// </summary>
    [Area("mes")]
    public class WorkOrderController : BaseController
    {

        private IWorkOrderService service;

        public WorkOrderController(IWorkOrderService _service)
        {
            service = _service;
        }
        //
        // GET: /AdjustOrder/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取产线
        /// </summary>
        /// <returns></returns>
        public ActionResult GetResourceCode()
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetResourceCode(factoryId);
            result.Add("list", menuList);
            return Json(result);
        }

        /// <summary>
        /// 工单类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrderType()
        {
           
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetOrderType();
            result.Add("list", menuList);
            return Json(result);
        }

        /// <summary>
        /// 工单状态
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrderStatus()
        {

            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetOrderStatus();
            result.Add("list", menuList);
            return Json(result);
        }

        /// <summary>
        /// 备料类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPrepareMateria()
        {

            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetPrepareMateria();
            result.Add("list", menuList);
            return Json(result);
        }
        /// <summary>
        /// 仓库
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWarehouse()
        {

            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetWarehouse();
            result.Add("list", menuList);
            return Json(result);
        }

        /// <summary>
        /// 获取工单管理列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getWorkOrderListPage(string orderNo, string partNo, string refWrokOrderNo, string resourceCode, string orderType, string orderStatus, string txtProduceStartTimeStart, string txtProduceStartTimeEnd, string txtProduceEndTimeStart, string txtProduceEndTimeEnd, Pager pager, string direction, string sort)
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            result.Add("pager.pageNo", pager.pageNo);
            Hashtable dataHt = service.getWorkOrderListPage(orderNo, partNo, refWrokOrderNo, resourceCode, orderType, orderStatus, txtProduceStartTimeStart, txtProduceStartTimeEnd, txtProduceEndTimeStart, txtProduceEndTimeEnd, factoryId, pager, direction, sort);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            result.Add("sort", sort);
            result.Add("direction", direction);
            return Json(result);
        }


        /// <summary>
        /// 将工单号传入配料页面
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult GenerateIngredients(List<String> orderNos)
        {
            if (orderNos.Count>0)
            {
                //List<SysWebMenu> menus = service.getMenuDetail(menuId);
                if (orderNos != null )
                {
                    //ViewData.Add("editType", "edit");
                    ViewData.Add("orderNos", orderNos[0]);

                }
            }
            else
            {
                //ViewData.Add("editType", "new");
            }
            return View("GenerateIngredients");
        }

        /// <summary>
        /// 保存备料数据
        /// </summary>
        /// <returns></returns>
        public ActionResult saveGenerateIngredients()
        {
            //String editType = Request.Form["editType"].ToString();
            SysWebMenu menu = new SysWebMenu();

            string prepareMaterial= Request.Form["prepareMaterial"].ToString();
            string orderNos= Request.Form["orderNos"].ToString();
            string Warehouse = Request.Form["Warehouse"].ToString();
            int empId = CurrentEmp.EmpId;


            String message = "";
            String flag = "";
            try
            {
              int t=  this.service.saveGenerateIngredients(prepareMaterial, orderNos, Warehouse, empId);
                if (t == 1)
                {
                    message = "备料成功";
                    flag = "OK";
                }
                else if (t == 0)
                {
                    message = "备料失败";
                    flag = "Fail";
                }
                else if (t == -1)
                {
                    message = "备料失败，选择的工单中，有已备料的工单";
                    flag = "Fail";
                }
                else if (t == -2)
                {
                    message = "有返修工单，请查看！";
                    flag = "Fail";
                }

                        
             
            }
            catch (Exception e)
            {
                message = "备料失败！";
                flag = "Fail";
            }

            Hashtable result = new Hashtable();
            result.Add("message", message);
            result.Add("flag", flag);
            return Json(result);

        }






        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="orderNos"></param>
        /// <returns></returns>
        public ActionResult onFiring(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.FiringData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 暂停
        /// </summary>
        /// <param name="orderNos"></param>
        /// <returns></returns>
        public ActionResult onSuspend(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.SuspendData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }


        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="orderNos"></param>
        /// <returns></returns>
        public ActionResult onCancel(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.CancelData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="orderNos"></param>
        /// <returns></returns>
        public ActionResult onClose(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.CloseData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 完成
        /// </summary>
        /// <param name="orderNos"></param>
        /// <returns></returns>
        public ActionResult onAccomplish(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.AccomplishData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }





        /*
        /// <summary>
        /// 获取生产指令调整列表数据
        /// </summary>
        /// <param name="CartonTrackName">菜单名称</param>
        /// <param name="pager">分页</param>
        /// <param name="direction">排序方式</param>
        /// <param name="sort">排序列</param>
        /// <returns></returns>
        public ActionResult getAdjustOrderListByPage(Pager pager, String direction, String sort, string cbCustPDLine, string SN, string partNo, String enabled = "Y")
        {
            if ((string.IsNullOrEmpty(cbCustPDLine)) || cbCustPDLine == "null")
            {
                cbCustPDLine = "0";
            }

            Hashtable result = new Hashtable();
            result.Add("pager.pageNo", pager.pageNo);
            Hashtable dataHt = this.service.getAdjustOrderListByPage(pager, direction, sort, cbCustPDLine, SN, partNo, enabled);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            result.Add("sort", sort);
            result.Add("direction", direction);
            return Json(result);
        }


        public ActionResult adjustLine(string seq, string ruid, string a, string SequenceNumber, string CustPDLine)
        {
            bool Bool = false;
            Hashtable result = new Hashtable();

            if (string.IsNullOrEmpty(seq) && string.IsNullOrEmpty(ruid) && string.IsNullOrEmpty(a))
            {
                result = new Hashtable();
                result.Add("status", false);
                return Json(result);
            }

            //选中行信息
            seq = seq.Substring(0, seq.Length - 1);
            ruid = ruid.Substring(0, ruid.Length - 1);
            int VirtualOrder = Convert.ToInt32(a.Substring(0, a.Length - 1));

            //查询所有待生产信息
            List<GWorkorderDetail> dt = this.service.selectAll(CustPDLine);

            var dr = dt.Find(a => a.Seq == Convert.ToInt32(SequenceNumber));

            int objectOrder = Convert.ToInt32(dr.A);

            if (Convert.ToInt32(VirtualOrder) > objectOrder)
            {
                for (int i = 0; i < VirtualOrder - objectOrder; i++)
                {

                    dt = new List<GWorkorderDetail>();
                    dt = this.service.selectAll(CustPDLine);
                    var dr_2 = dt.Find(x => x.A == (VirtualOrder - i));
                    var dr_3 = dt.Find(x => x.A == (Convert.ToInt32(VirtualOrder) - i - 1));

                    int data_ruid_1 = Convert.ToInt32(dr_2.Ruid);
                    int data_seq_1 = Convert.ToInt32(dr_2.Seq);
                    int data_ruid_2 = Convert.ToInt32(dr_3.Ruid);
                    int data_seq_2 = Convert.ToInt32(dr_3.Seq);

                    Bool = this.service.upAll(data_ruid_1, data_seq_1, data_ruid_2, data_seq_2);
                }
            }
            else
            {
                result = new Hashtable();
                result.Add("status", false);
                return Json(result);
            }

            result = new Hashtable();
            result.Add("status", true);
            return Json(result);
        }


        /// <summary>
        /// 删除BOMdetail数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult deleteOrder(string ruid)
        {
            int delCount = 0;
            Hashtable result = new Hashtable();
            ruid = ruid.Substring(0, ruid.Length - 1);

            try
            {
                delCount = this.service.deleteOrder(ruid);
                if (delCount > 0)
                {
                    result.Add("message", "删除成功！");
                }
                else
                {
                    result.Add("message", "删除失败！");
                }
            }
            catch (Exception e)
            {
                delCount = -1;
            }

            return Json(result);
        }

        public ActionResult deleteOrderInfo(string ruid)
        {
            String[] array = ruid.Split(',');
            ruid = array[0].ToString();
            string custPdlineDesc = array[1].ToString();

            int delCount = 0;
            Hashtable result = new Hashtable();

            try
            {
                delCount = this.service.deleteOrderInfo(ruid, custPdlineDesc);
                if (delCount > 0)
                {
                    result.Add("message", "删除成功！");
                }
                else
                {
                    result.Add("message", "删除失败！");
                }
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            return Json(result);
        }

        /// <summary>
        /// 启用
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult onEnable(String ids)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.EnableData(ids);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult onDisable(String ids)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.DisableData(ids);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }
        */
        /*
        /// <summary>
        /// 导出数据到Excel
        /// BY NOAH
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="txtOrderNo"></param>
        /// <param name="sort"></param>
        /// <param name="direction"></param>
        /// <param name="isPage"></param>
        /// <returns></returns>
        public ActionResult exportData(String cbCustPDLine, Pager pager, String sort, String direction, String isPage)
        {
            Boolean paging = false;
            if (isPage == null || "".Equals(isPage))
            {
                paging = false;
            }
            else
            {
                if ("1".Equals(isPage.Trim()))
                {
                    paging = true;
                }
                else
                {
                    paging = false;
                }
            }
            Hashtable dataHt = this.service.getTableListByPage(cbCustPDLine, pager, direction, sort, paging);
            List<AdjustOrder> listHt = (List<AdjustOrder>)dataHt["dataList"];
            var memoryStream = ExcelHelper.ToExcel(listHt);
            return File(memoryStream.ToArray(), "application/ms-excel", "生产指令调整.xls");
        }


        */

    }


}
